/*
   This file is part of the 'Let's Do Stuff Together' project
   http://code.google.com/p/dostufftogether/

   Copyright 2010 Christoph Fuchs, Stefan Thaler

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
 */
package org.sti2.letsdostuff;

import org.sti2.letsdostuff.util.QueryHelper;
import org.sti2.letsdostuff.util.UrlHelper;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

/**
 * TODO Describe this type briefly. If necessary include a longer description
 * and/or an example.
 * 
 * @author gigi
 * 
 */
public class HelloWebView extends Activity {

	/** Called when the activity is first created. */
	WebView webview;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.webview);
		webview = (WebView) findViewById(R.id.webview);
		Log.v("WebView", "Found web view: " + webview);
		webview.setWebViewClient(new HelloWebViewClient());
		webview.getSettings().setJavaScriptEnabled(true);
		
		/* Register a new JavaScript interface called HTMLOUT */  
		webview.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");
		
		webview.loadUrl(UrlHelper.generateGoogleAccountOpenIDauthURL());
	}

	private class HelloWebViewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			return true;
		}
		
		/* (non-Javadoc)
		 * @see android.webkit.WebViewClient#onLoadResource(android.webkit.WebView, java.lang.String)
		 */
		@Override
		public void onLoadResource(WebView view, String url) {
			super.onLoadResource(view, url);
			Log.v("WebView", "Loading url " + url);
//			String responseBody = QueryHelper.queryServer(getApplicationContext(), ServerConfiguration.GOOGLE_LOGIN_CHECK);
			String responseBody = QueryHelper.queryServer(getApplicationContext(), url);
			Log.v("WebView", "Response body: " + responseBody);
			if (responseBody != null && responseBody.equals("true")) {
				Log.v("WebView", "AUTHENTICATED");
				StringBuilder sb = new StringBuilder();
				sb.append("<html>");
				sb.append("<body>");
				sb.append("<h3>Success!</h3>");
				sb.append("<p>You have been authenticated using your Google openID. Please return to the application by pressing the back button on your android phone.</p>");
				sb.append("</body>");
				sb.append("</html>");
				view.loadData(sb.toString(), "text/xml", "utf-8");
			}
		}
		
		/* (non-Javadoc)
		 * @see android.webkit.WebViewClient#onPageFinished(android.webkit.WebView, java.lang.String)
		 */
		@Override
		public void onPageFinished(WebView view, String url) {
			super.onPageFinished(view, url);
			/* This call inject JavaScript into the page which just finished loading. */  
	        webview.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
	        
		}
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
			webview.goBack();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/* An instance of this class will be registered as a JavaScript interface */  
	class MyJavaScriptInterface  
	{  

		public void showHTML(String html)  
	    {  
	        Log.v("WebView", "GOT HTML: " + html);
	        if (html.contains("<head><head></head><body>true</body></head>")) {
	        	Log.v("WebView", "AUTHENTICATED");
	        	LetsDoStuff.isLoggedIn = true;
	        	
	        	/*
	        	 * Forward user to create activity view
	        	 */
	        	Log.i("View", "Switching to create activity view");
				Intent createActivityIntent = new Intent(getBaseContext(), CreateActivity.class);
				startActivity(createActivityIntent);
	        }
	    }  
	} 
}
